#!/usr/bin/env bash
set -euo pipefail

echo "🧪 测试多Agent协作系统"
echo "========================"

# 检查所有服务是否运行
echo "📊 检查服务状态..."
PORTS=(7001 7003 7004 7005 7006 7007 8000 8080)
AGENT_NAMES=("MCP" "Weather" "Travel" "Restaurant" "Coordinator" "Budget" "WebBackend" "WebFrontend")

all_running=true
for i in "${!PORTS[@]}"; do
    port=${PORTS[$i]}
    name=${AGENT_NAMES[$i]}
    if lsof -i :${port} >/dev/null 2>&1; then
        echo "  ✅ ${name}Agent (${port})"
    else
        echo "  ❌ ${name}Agent (${port}) - 未运行"
        all_running=false
    fi
done

if [ "$all_running" = false ]; then
    echo "❌ 部分服务未运行，请先启动所有Agent"
    echo "💡 运行: ./start_all_agents_uv.sh"
    exit 1
fi

echo ""
echo "✅ 所有Agent服务正常运行"

echo ""
echo "🧪 测试1: Agent状态检查"
echo "------------------------"
response=$(curl -s "http://localhost:8000/agents/status" | python -m json.tool)
echo "$response"

echo ""
echo "🧪 测试2: Weather Agent 协作请求"
echo "-------------------------------"
echo "发送协作请求到WeatherAgent (Beijing)..."

weather_response=$(curl -s -X POST "http://localhost:7003/a2a/tasks/send" \
  -H "Content-Type: application/json" \
  -d '{
    "message": {
      "content": {
        "text": "{\"type\":\"collaboration_request\",\"user_requirements\":{\"location\":\"Beijing\"},\"collaboration_context\":{\"purpose\":\"travel_planning\"}}"
      }
    }
  }')

echo "Weather响应摘要:"
echo "$weather_response" | python -c "
import json, sys
data = json.load(sys.stdin)
text = data['artifacts'][0]['parts'][0]['text']
weather_data = json.loads(text)
print(f\"  城市: {weather_data['weather_data']['city']}\")
print(f\"  标准化城市: {weather_data['weather_data']['normalized_city']}\")
print(f\"  当前天气: {weather_data['weather_data']['current'][:60]}...\")
print(f\"  数据源: {weather_data['weather_data']['data_source']}\")
print(f\"  协商点数量: {len(weather_data['negotiation_points'])}\")
print(f\"  潜在冲突: {len(weather_data['potential_conflicts'])}\")
"

echo ""
echo "🧪 测试3: Budget Agent 协作请求"
echo "------------------------------"
echo "发送预算分析请求到BudgetAgent..."

budget_response=$(curl -s -X POST "http://localhost:7007/a2a/tasks/send" \
  -H "Content-Type: application/json" \
  -d '{
    "message": {
      "content": {
        "text": "{\"type\":\"collaboration_request\",\"user_requirements\":{\"budget\":\"800\",\"location\":\"Beijing\",\"duration\":\"3天\"},\"upstream_context\":{\"weather_impact\":{\"extra_transportation_cost\":50,\"equipment_cost\":30}},\"collaboration_context\":{\"purpose\":\"travel_planning\"}}"
      }
    }
  }')

echo "Budget响应摘要:"
echo "$budget_response" | python -c "
import json, sys
data = json.load(sys.stdin)
text = data['artifacts'][0]['parts'][0]['text']
budget_data = json.loads(text)
analysis = budget_data['budget_data']
print(f\"  基础预算: {analysis['base_budget']}\")
print(f\"  总需求: {analysis['total_required']}\")
print(f\"  预算状态: {analysis['budget_status']}\")
print(f\"  协商点数量: {len(budget_data['negotiation_points'])}\")
if 'budget_alternatives' in budget_data:
    print(f\"  替代方案: {len(budget_data['budget_alternatives'])}\")
else:
    print(f\"  替代方案: 0\")
"

echo ""
echo "🧪 测试4: Coordinator 完整协作流程"
echo "--------------------------------"
echo "发送完整旅行规划请求到Coordinator..."

coord_response=$(curl -s -X POST "http://localhost:7006/a2a/tasks/send" \
  -H "Content-Type: application/json" \
  -d '{
    "message": {
      "content": {
        "text": "我想去北京旅行3天，预算800欧元，喜欢历史景点和美食，对天气比较敏感"
      }
    }
  }')

echo "Coordinator响应片段 (前500字符):"
echo "$coord_response" | python -c "
import json, sys
data = json.load(sys.stdin)
text = data['artifacts'][0]['parts'][0]['text']
print(text[:500] + ('...' if len(text) > 500 else ''))
"

echo ""
echo "🧪 测试5: 前端界面可用性"
echo "------------------------"
frontend_status=$(curl -s -w "%{http_code}" -o /dev/null "http://localhost:8080")
if [ "$frontend_status" = "200" ]; then
    echo "✅ 前端界面可访问: http://localhost:8080"
else
    echo "❌ 前端界面访问失败 (HTTP ${frontend_status})"
fi

backend_health=$(curl -s "http://localhost:8000/health")
echo "✅ 后端健康检查: $backend_health"

echo ""
echo "🎉 多Agent协作系统测试完成！"
echo ""
echo "🔗 访问链接:"
echo "  📱 协作界面: http://localhost:8080"
echo "  📖 API文档: http://localhost:8000/docs"
echo "  📊 Agent状态: http://localhost:8000/agents/status"
echo ""
echo "💡 Agent协作特点:"
echo "  🌤️  WeatherAgent: 提供天气数据 + 影响分析 + 协商点"
echo "  💰 BudgetAgent: 预算分析 + 成本优化 + 主动协商"
echo "  🎯 Coordinator: 意图分析 + 执行编排 + 冲突解决"
echo "  🔄 协商循环: Agent间自动协商和方案优化"
echo ""
echo "🧪 下一步测试建议:"
echo "  1. 打开前端界面测试完整用户流程"
echo "  2. 查看 logs/ 目录下的Agent日志"
echo "  3. 尝试不同的旅行需求触发协商"
